package ge.devfest.hackathon.gg.json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;

import android.os.Build;
import android.util.Log;

public abstract class JSONParser {

        protected static final String TAG = "JSONParser";
       
        public static JSONParser getInstance() {
                /*
                 * according to this ->
                 * http://android-developers.blogspot.com/2011/09/androids
                 * -http-clients.html guide we need to choose implementation depending
                 * on android version
                 */
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                        Log.v(TAG, "Android versionn newer(equal) than gingerbread");
                        return new PostGingerbreadJSONParser();
                } else {
                        Log.v(TAG, "Android versionn older than gingerbread");
                        return new PreGingerbreadJSONParser();
                }
        }

        /**
         * Parses resource at specified url and returns {@link JSONArray}
         *
         * @param url
         *            - url of the resource
         **/
        public JSONArray parse(String url) throws JSONException, IOException {
                try {
                        InputStream in = getInputStream(url);
                        return new JSONArray(readToEnd(in));
                } finally {
                        release();
                }
        }
        
        private String readToEnd(InputStream in) throws IOException {
                if (in == null) {
                        throw new RuntimeException("Unable to read null InputStream");
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int read;
                while ((read = in.read(buff)) != -1) {
                        bos.write(buff, 0, read);
                }
                return new String(bos.toByteArray());
        }

        public abstract InputStream getInputStream(String url)
                        throws IOException;
       
        public abstract void release();

}